package com.my.tool.lucky.util;

import com.my.tool.lucky.model.MagicBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MagicNumberTool {

    private Logger logger = LoggerFactory.getLogger(MagicNumberTool.class);

    /**
     *
     * @param magicBox
     * @return
     */
    public List<Integer> shake(MagicBox magicBox) {
        int boolSize = magicBox.getPullBallSize();
        logger.info("hello, let us to pull ball :{}", magicBox);
        List<Integer> hengKeys = new ArrayList<>(boolSize);
        for(int index = 0; index < boolSize; index++) {
            int ballNumber = giveBall(hengKeys, 0, magicBox);
            hengKeys.add(ballNumber);
            logger.info("hi, the {} {} ball is: {}", (index+1), magicBox.getKey(), ballNumber);
        }
        logger.info("hello, {} ball is ok ... ", magicBox.getKey());
        return hengKeys;
    }

    private int giveBall(List<Integer> hengKeys, int seq, MagicBox magicBox) {
        int key0 = magicBox.getLucyStar().nextInt(magicBox.getBallTotal());
        if(key0==0 || hengKeys.contains(key0)) {
            return giveBall(hengKeys, seq, magicBox);
        }

        List<Integer> black = new ArrayList<>(hengKeys);
        black.add(key0);
        black = black.stream().sorted().collect(Collectors.toList());
        // 检测是否存在连续号4个以上的
        if(checkSerial(black, magicBox.getSerialLimit())) {
            return giveBall(hengKeys, seq, magicBox);
        }

        seq = seq + 1;
        if(seq == magicBox.getLucyNumber()) {
            int key = key0;
            return key;
        }

        return giveBall(hengKeys, seq, magicBox);
    }

    private boolean checkSerial(List<Integer> ballBox, int serialLimit) {
        int ballSize = ballBox.size();
        if(ballSize < serialLimit) {
            return false;
        }

        List<Integer> serialNums = new ArrayList<>(serialLimit);
        for(int index = 0; index <= ballSize - serialLimit; index++) {
//            int num1 = black.get(index);
//            int num2 = black.get(index + 1);
//            int num3 = black.get(index + 2);
//            int num4 = black.get(index + 3);
//
//            if(num2-num1==1 && num3-num2==1 && num4-num3==1) {
//                return true;
//            }

            for(int seq = 0; seq < serialLimit; seq++) {
                serialNums.add(ballBox.get(index+seq));
            }
            boolean serialSign = false;
            for(int seq = 0; seq < serialLimit - 1; seq++) {
                int one = serialNums.get(seq);
                int two = serialNums.get(seq + 1);
                serialSign = (two - one == 1);
                if( !serialSign) {
                    break;
                }
            }
            if(serialSign) {
                return true;
            }
        }
        return false;
    }
}
